package com.nanako.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nanako.common.BaseContext;
import com.nanako.common.R;
import com.nanako.dto.OrdersDto;
import com.nanako.entity.Orders;
import com.nanako.entity.User;
import com.nanako.entity.UserOrdersExport;
import com.nanako.service.OrderDetailService;
import com.nanako.service.OrderService;
import com.nanako.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("/userPage")
    public R queryOrder(Integer page, Integer pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        orderService.page(ordersPage, wrapper);
        //List<Orders> records = ordersPage.getRecords();
        //List<OrderDetail> orderDetails = records.stream().map(order -> {
        //    Long orderId = order.getId();
        //    LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
        //    orderDetailWrapper.eq(OrderDetail::getOrderId, orderId);
        //    return orderDetailService.getOne(orderDetailWrapper);
        //}).toList();
        //return R.success(new Page<OrderDetail>().setRecords(orderDetails));
        return R.success(ordersPage);
    }

    @GetMapping("/page")
    public R queryBackendOrder(Integer page, Integer pageSize, Long number, String beginTime, String endTime) {
        log.info("起始日期:{}", beginTime);
        log.info("截至日期:{}", endTime);


        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtils.isNotEmpty(number), Orders::getNumber, number)
                .between(ObjectUtils.allNotNull(beginTime, endTime), Orders::getOrderTime, beginTime, endTime);
        orderService.page(ordersPage, wrapper);
        List<OrdersDto> ordersDtos = ordersPage.getRecords().stream().map(order -> {
            OrdersDto ordersDto = new OrdersDto();
            Orders queryOrder = orderService.getById(order.getId());
            User user = userService.getById(queryOrder.getUserId());
            BeanUtils.copyProperties(order, ordersDto);
            ordersDto.setUserName(user.getName());
            return ordersDto;
        }).toList();
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        ordersDtoPage.setRecords(ordersDtos);
        return R.success(ordersDtoPage);
    }

    @PutMapping
    public R updateOrderStatus(@RequestBody Map order) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getNumber, order.get("id"));
        Orders queryOrder = orderService.getOne(wrapper);
        if (ObjectUtils.isNotEmpty(queryOrder)) {
            queryOrder.setStatus((Integer) order.get("status"));
            orderService.updateById(queryOrder);
            return R.success("派送成功");
        }
        return R.error("派送失败");
    }

    @GetMapping("/export")
    public void executeExport(HttpServletResponse response) throws IOException {

        List<Orders> ordersList = orderService.list();
        //生成数据
        List<UserOrdersExport> UserOrderExports = new ArrayList<>();
        for (int i = 0; i < ordersList.size() && i < 50; i++) {
            Orders order = ordersList.get(i);
            String status = "";
            switch (order.getStatus()) {
                case 1 -> status = "待付款";
                case 2 -> status = "待派送";
                case 3 -> status = "已派送";
                case 4 -> status = "已完成";
                case 5 -> status = "已取消";
            }
            UserOrdersExport UserOrderExport = UserOrdersExport.builder()
                    .orderNumber(order.getNumber())
                    .orderStatus(status)
                    .userPhone(order.getPhone())
                    .address(order.getAddress())
                    .orderTime(order.getOrderTime())
                    .amount(order.getAmount())
                    .checkOutTime(order.getCheckoutTime())
                    .consignee(order.getConsignee())
                    .remark(order.getRemark())
                    .username(order.getUserName()).build();
            UserOrderExports.add(UserOrderExport);
        }

        response.setContentType("application/vnd.ms-excel");

        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("订单明细", StandardCharsets.UTF_8);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), UserOrdersExport.class)
                .sheet("sheet0")
                .doWrite(UserOrderExports);
    }

    /**
     * 再来一单
     */
    @PostMapping("/again")
    public R again() {
        return null;
    }
}